package main

import (
	"log"
	"os"
	"spark-port-proxy/util"
	"strconv"
	"sync"
	"time"
)

const (
	broadcastAddress = "255.255.255.255" // 广播地址
	broadcastPort    = 12345     // 广播端口
	broadcastInterval = 5 * time.Second
	portRangeStart   = 8000      // 分配端口范围的起始值
	portRangeEnd     = 9000      // 分配端口范围的结束值
)



var (
	nodes        = make(map[string]Node) // 存储节点信息的映射表，key为节点IP地址
	nodesMutex   sync.Mutex              // 保护节点映射表的互斥锁
	nextNodeID   = 1                      // 下一个可用的节点ID
	nextPort     = portRangeStart         // 下一个可用的端口号
	nextPortLock sync.Mutex              // 保护下一个可用端口的互斥锁
	queue        = make(chan ReceivePackage, 10)
)

func main() {

	hostname, err := os.Hostname()
	if err != nil {
		log.Println("无法获取主机名:", err)
		return
	}
	ip := util.GetIP()
	if ip == "127.0.0.1" {
		log.Println("无法获取主机ip:")
		return
	}

	startPort := os.Getenv("PROXY_START_PORT")
	if startPort == "" {
		startPort = "5011"
	}
	portNums := os.Getenv("PROXY_PORT_NUMS")
	if portNums == "" {
		portNums = "16"
	}
	proxyPorts, err := strconv.Atoi(portNums)
	if err != nil || proxyPorts <= 0 {
		log.Println("PROXY_PORT_NUMS error:", portNums)
		return
	}
	log.Println("start on " + hostname, "and", ip)
	server := Server{
		Queue:            queue,
		BroadcastAddress: broadcastAddress,
		Port:             broadcastPort,
		HttpPort:         8080,
		Interval:         5,
		ProxyStartPort:   startPort,
		ProxyPorts:       proxyPorts,
		Hostname:         hostname,
		IP: ip,
	}

	server.Serve()
}